<?php

// 应用公共文件

/**
 * 特殊字符过滤
 *
 * @param $str
 * @return array|string
 */
function xssReplaceStr($str): array|string
{
    $xpd = explode(',', '(,), ,<,>,\\,*,&,%,$,^,[,],{,},!,@,#,",+,?,;\'');
    $xpd[] = "\n";
    return str_ireplace($xpd, '', $str);
}

/**
 * 获取访问的浏览器
 *
 * @return string
 */
function getBrowser(): string
{
    $web = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $browser = 'IE';
    $parr = [
        ['MSIE 5'],
        ['MSIE 6'],
        ['XIAOMI', 'xiaomi'],
        ['HUAWEI', 'huawei'],
        ['XINHUAPP', 'xinhu'],
        ['DingTalk', 'ding'],
        ['MSIE 7'],
        ['MSIE 8'],
        ['MSIE 9'],
        ['MSIE 10'],
        ['MSIE 11'],
        ['rv:11', 'MSIE 11'],
        ['MSIE 12'],
        ['HuaWei - AnyOffice', 'welink'],
        ['MicroMessenger', 'wxbro'],
        ['MSIE 13'],
        ['Firefox'],
        ['OPR / ', 'Opera'],
        ['Edge'],
        ['MQQBrowser', 'mqq'],
        ['Chrome'],
        ['Safari'],
        ['Android'],
        ['iPhone'],
    ];

    foreach ($parr as $wp) {
        if (contain($web, $wp[0])) {
            $browser = $wp[0];
            if (isset($wp[1])) {
                $browser = $wp[1];
            }
            break;
        }
    }

    $web = strtolower($web);
    if (contain($web, 'micromessenger')) {
        $browser = 'wxbro'; //微信浏览器
    }
    if (contain($web, 'dingtalk')) {
        $browser = 'ding'; //钉钉浏览器
    }

    return $browser;
}

/**
 * 判断字符串是否包含另一个字符串
 *
 * @param string $string1 查询的字符串
 * @param string $string2 被包含的字符串
 * @return bool
 */
function contain(string $string1, string $string2): bool
{
    $bool = false;
    if (!empty($string1) && !empty($string2)) {
        $res = strpos($string1, $string2);
        if ($res > 0 || !is_bool($res)) {
            $bool = true;
        }
    }
    return $bool;
}

/**
 * 获取IP地址
 *
 * @return string
 */
function getClientIP(): string
{
    $ip = 'unknown';
    if (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } else if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else if (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }

    return htmlspecialchars(xssReplaceStr($ip));
}